package com.tangcheng.user.adapter.security;

import com.tangcheng.user.business.user.service.RememberMeDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

/**
 * @Auther: cheng.tang
 * @Date: 2023/10/2
 * @Description: mybatis-subject
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/jwt/login").permitAll()
                .antMatchers("/view/jwt/**").permitAll()
                .antMatchers("/remberme/login").permitAll()
                .antMatchers("/sec/admin/**").hasRole("ADMIN") // 需要ADMIN角色才能访问/admin路径
                .antMatchers("/sec/user/**").hasRole("USER") // 需要USER角色才能访问/user路径
                .and().formLogin().loginPage("/remberme/login") // 登录页的URL
                .defaultSuccessUrl("/remberme/profile")
                .and()
                .rememberMe()
                .tokenRepository(tokenRepository())
                .userDetailsService(userDetailsService())
                .and().logout().permitAll();
        return http.build();
    }


    @Bean
    public UserDetailsService userDetailsService() {
        return new RememberMeDetailsService();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public JdbcTokenRepositoryImpl tokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        tokenRepository.setCreateTableOnStartup(false);
        return tokenRepository;
    }


}
